package com.btex.app.treaty;

import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.btex.app.BaseActivity;
import com.btex.app.Config;
import com.btex.app.R;
import com.btex.app.entity.FuturesAccountListsInfo;
import com.btex.app.tools.CookieTool;
import com.btex.app.tools.MicroAVLIDialog;
import com.btex.app.tools.SharedPreferencesUtil;
import com.btex.app.tools.Tools;
import com.btex.app.tools.Util;
import com.btex.app.treaty.dialog.ZhiJingZhuanDialog;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MoneyTransfersActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_otc_la)
    ImageView mTvOtcLa;
    @BindView(R.id.tv_menu)
    TextView mTvMenu;
    @BindView(R.id.rl_title)
    RelativeLayout mRlTitle;
    @BindView(R.id.dialog_traety_unwind_tv_sure)
    TextView mDialogTraetyUnwindTvSure;
    @BindView(R.id.activity_treaty_two_spinner)
    Spinner mActivityTreatyTwoSpinner;
    @BindView(R.id.activity_treaty_all_spinner)
    Spinner mActivityTreatyAllSpinner;
    @BindView(R.id.activity_treaty_one_spinner)
    Spinner mActivityTreatyOneSpinner;
    @BindView(R.id.dialog_traety_unwind_tv_all)
    TextView mDialogTraetyUnwindTvAll;
    @BindView(R.id.activity_treaty_ed_number)
    EditText mActivityTreatyEdNumber;
    @BindView(R.id.dialog_traety_unwind_tv_one)
    TextView mDialogTraetyUnwindTvOne;
    @BindView(R.id.dialog_traety_unwind_tv_two)
    TextView mDialogTraetyUnwindTvTwo;
    @BindView(R.id.activity_treaty_suoyou_tv)
    TextView activity_treaty_suoyou_tv;
    @BindView(R.id.activity_treaty_suoyou)
    LinearLayout mActivityTreatySuoyou;
    @BindView(R.id.money_dialog_password)
    EditText mMoneyDialogPassword;
    private ArrayList<String> mStrings;
    private ArrayList<String> one;
    private ArrayList<String> two;


    private String mSelectedItem = "BTC";
    private String mOneItem;
    private String mTwoItem;
    private String mtype;
    private MicroAVLIDialog mMicroAVLIDialog;
    private List<FuturesAccountListsInfo.DataBean> mData;
    private double mBalance1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_money_transfers);
        ButterKnife.bind(this);
        String mSettle_anchor = getIntent().getExtras().getString("mSettle_anchor");
        activity_treaty_suoyou_tv.setText(mSettle_anchor);
        mSelectedItem = mSettle_anchor;
        mMicroAVLIDialog = new MicroAVLIDialog(this);
        getInfo();
        mTvTitle.setText("资金划转");

        initone();
        inittwo();
        initListener();
        mActivityTreatyEdNumber.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(Integer.valueOf(8))});
    }

    private void inittwo() {
        two = new ArrayList<>();
        two.add(getString(R.string.bibi_yonghu));
        two.add(getString(R.string.heyue_zhanghu));


        String[] string = two.toArray(new String[two.size()]);
        //将可选内容与ArrayAdapter连接起来
        ArrayAdapter<String> adapter = new ArrayAdapter<>(MoneyTransfersActivity.this, R.layout.my_spinner, string);
        //设置下拉列表的风格
        adapter.setDropDownViewResource(R.layout.my_spinner_view);

        mActivityTreatyTwoSpinner.setAdapter(adapter);
    }

    private void initone() {

        one = new ArrayList<>();
        one.add(getString(R.string.bibi_yonghu));
        one.add(getString(R.string.heyue_zhanghu));


        String[] string = one.toArray(new String[one.size()]);
        //将可选内容与ArrayAdapter连接起来
        ArrayAdapter<String> adapter = new ArrayAdapter<>(MoneyTransfersActivity.this, R.layout.my_spinner, string);
        //设置下拉列表的风格
        adapter.setDropDownViewResource(R.layout.my_spinner_view);

        mActivityTreatyOneSpinner.setAdapter(adapter);
    }

    private void initAll(List<FuturesAccountListsInfo.DataBean> data) {

        mStrings = new ArrayList<>();

        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getType_info().equals(getString(R.string.heyue_zhanghu))) {

                for (int j = 0; j < data.get(i).getBalance().size(); j++) {

                    String symbol = data.get(i).getBalance().get(j).getSymbol();
                    mStrings.add(symbol);
                }
            }
        }

        Log.i("weofkwpkefp", mStrings.toString());
//
//        String[] string = mStrings.toArray(new String[mStrings.size()]);
//        //将可选内容与ArrayAdapter连接起来
//        ArrayAdapter<String> adapter = new ArrayAdapter<>(MoneyTransfersActivity.this, R.layout.my_spinner, string);
//        //设置下拉列表的风格
//        adapter.setDropDownViewResource(R.layout.my_spinner_view);
//
//        mActivityTreatyAllSpinner.setAdapter(adapter);


    }

    private void initListener() {

        mActivityTreatySuoyou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ZhiJingZhuanDialog historyDialog = new ZhiJingZhuanDialog(MoneyTransfersActivity.this);
                historyDialog.setData(mStrings);
                historyDialog.getValue(new ZhiJingZhuanDialog.ZhangHu() {
                    @Override
                    public void get(String data) {
                        mSelectedItem = data;
                        getValue();
                        getTwoValue();
                        activity_treaty_suoyou_tv.setText(mSelectedItem);
                    }
                });
                historyDialog.show();
            }
        });


        mActivityTreatyTwoSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mTwoItem = (String) mActivityTreatyTwoSpinner.getSelectedItem();


                int selectedItemPosition = mActivityTreatyTwoSpinner.getSelectedItemPosition();
                if (selectedItemPosition == 0) {
                    mActivityTreatyOneSpinner.setSelection(1);
                } else {
                    mActivityTreatyOneSpinner.setSelection(0);
                }
                getTwoValue();

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        mActivityTreatyAllSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {


                mSelectedItem = (String) mActivityTreatyAllSpinner.getSelectedItem();
                getValue();
                getTwoValue();

                Log.i("wleifweioiwjef", mSelectedItem);


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {


            }
        });


        mActivityTreatyOneSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                Log.i("lweijowiefjowie", "1");
                mOneItem = (String) mActivityTreatyOneSpinner.getSelectedItem();


                int selectedItemPosition = mActivityTreatyOneSpinner.getSelectedItemPosition();
                if (selectedItemPosition == 0) {
                    mActivityTreatyTwoSpinner.setSelection(1);
                } else {
                    mActivityTreatyTwoSpinner.setSelection(0);
                }

                getValue();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }


    @Override
    public void setData() {

    }

    @Override
    public void onClick(View v) {

    }

    @OnClick({R.id.iv_back, R.id.tv_title, R.id.dialog_traety_unwind_tv_sure, R.id.dialog_traety_unwind_tv_all})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_title:
                break;
            case R.id.dialog_traety_unwind_tv_sure:

                if (!TextUtils.isEmpty(mActivityTreatyEdNumber.getText())) {

                    if (mOneItem.equals(mTwoItem)) {
                        Toast.makeText(cxt, "请选择不同类型的账户!", Toast.LENGTH_SHORT).show();
                    } else {
                        if (mOneItem.equals("币币账户")) {
                            mtype = "cash_mx";
                        } else {
                            mtype = "mx_cash";
                        }

                        setAccountTransfer(mtype);
                    }


                } else {

                    Toast.makeText(cxt, "数量不能为空", Toast.LENGTH_SHORT).show();
                }


                break;
            case R.id.dialog_traety_unwind_tv_all:

//                mBalance1

                mActivityTreatyEdNumber.setText(mBalance1 + "");


                break;
        }
    }

    private void setAccountTransfer(String mtype) {


        String trim = mMoneyDialogPassword.getText().toString().trim();
        if (TextUtils.isEmpty(trim)) {
            Toast.makeText(this, "请输入交易密码", Toast.LENGTH_SHORT).show();
            return;
        }

        if (mMicroAVLIDialog != null) {
            mMicroAVLIDialog.show();
        }

        Log.i("wkejwoeijowe", mtype);

        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(this);
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(this, sharedPreferences);
        RequestParams params = new RequestParams();
        params.addBodyParameter("transfer", mtype);
        params.addBodyParameter("type", mSelectedItem);
        params.addBodyParameter("amount", mActivityTreatyEdNumber.getText().toString());
        params.addBodyParameter("trade_psw", mMoneyDialogPassword.getText().toString().trim());
        params.addHeader("myclient", "android");

        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.POST, Config.ACCOUNT_TRANSFER, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                if (mMicroAVLIDialog != null) {
                    mMicroAVLIDialog.dismiss();
                }

                Log.i("nbvefuweifuhwieufiwef", responseInfo.result);
                try {
                    JSONObject jsonObject = new JSONObject(responseInfo.result);

                    if (jsonObject.getString("code").equals("1")) {

                        if (mActivityTreatyEdNumber != null) {
                            mActivityTreatyEdNumber.setText("");
                        }

                        if (mMoneyDialogPassword != null) {
                            mMoneyDialogPassword.setText("");
                        }

                        getInfo();
                        Util.showSnachBar(MoneyTransfersActivity.this, getResources().getColor(R.color.bg_green), "操作成功");

                    } else {
                        Util.showSnachBar(MoneyTransfersActivity.this, getResources().getColor(R.color.red), jsonObject.getString("info"));
                    }
                } catch (JSONException e) {


                }

            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }

        });
    }


    private void getInfo() {

        if (mMicroAVLIDialog != null) {
            mMicroAVLIDialog.show();
        }


        SharedPreferencesUtil sharedPreferences = SharedPreferencesUtil.getSharedPreferences(this);
        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(this, sharedPreferences);
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("lang", "zh_cn");
        params.addHeader("myclient", "android");
        int num = (int) ((Math.random() * 9 + 1) * 100000);

        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.ACCOUNT_LISTS + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                Log.i("hfufhhwieh", responseInfo.result);

                if (mMicroAVLIDialog != null) {
                    mMicroAVLIDialog.dismiss();
                }

                try {
                    JSONObject jsonObj = new JSONObject(responseInfo.result);
                    if (jsonObj.getString("code").equals("1")) {

                        setInfo(responseInfo.result);
//                        initone();
//                        inittwo();
                        getValue();
                        getTwoValue();

                    } else {

                    }


                } catch (JSONException e) {
                    e.printStackTrace();

                }


            }

            @Override
            public void onFailure(HttpException error, String msg) {


            }

        });


    }

    private void setInfo(String result) {

        Gson gson = new Gson();
        FuturesAccountListsInfo futuresAccountListsInfo = gson.fromJson(result, FuturesAccountListsInfo.class);
        mData = futuresAccountListsInfo.getData();

        Log.i("wewefwief", mData.size() + "");

        initAll(mData);

    }

    public void getValue() {

        if (mData != null) {

            if (mActivityTreatyOneSpinner.getSelectedItem().equals(getString(R.string.bibi_yonghu))) {
                mOneItem = "币币账户";

            } else {
                mOneItem = "合约账户";

            }

            String value = "0";

            for (int i = 0; i < mData.size(); i++) {

                String type_info = mData.get(i).getType_info();

                Log.i("jwbfkewhefwfuyqfberf", type_info);

                if (mOneItem.equals(type_info)) {

                    List<FuturesAccountListsInfo.DataBean.BalanceBean> balance = mData.get(i).getBalance();
                    String symbol = balance.get(0).getSymbol();
                    for (int j = 0; j < balance.size(); j++) {

                        String symbol1 = balance.get(j).getSymbol();

                        if (mSelectedItem.equals(balance.get(j).getSymbol())) {
                            mBalance1 = balance.get(j).getBalance();
//                            value = balance.get(j).getBalance() + "";
                            if ((balance.get(j).getBalance() == 0)) {
                                value = "0.00";
                            } else {
                                value = Tools.round(balance.get(j).getBalance(), 8).toString();
                            }

                        }

                    }

                    mDialogTraetyUnwindTvOne.setText(value + "" + mSelectedItem);

                }
            }

        }

    }


    public void getTwoValue() {
        if (mData != null) {

            String selectedItem = (String) mActivityTreatyTwoSpinner.getSelectedItem();


            if (mActivityTreatyTwoSpinner.getSelectedItem().equals(getString(R.string.bibi_yonghu))) {
                mTwoItem = "币币账户";
            } else {
                mTwoItem = "合约账户";

            }

            String value = "0";

            for (int i = 0; i < mData.size(); i++) {

                String type_info = mData.get(i).getType_info();
                Log.i("weofpwoekf", type_info);

                if (mTwoItem.equals(type_info)) {

                    List<FuturesAccountListsInfo.DataBean.BalanceBean> balance = mData.get(i).getBalance();
                    for (int j = 0; j < balance.size(); j++) {

                        if (mSelectedItem.equals(balance.get(j).getSymbol())) {
//                            value = balance.get(j).getBalance() + "";
                            if (balance.get(j).getBalance() == 0) {
                                value = "0.00";
                            } else {
                                value = Tools.round(balance.get(j).getBalance(), 8).toString();
                            }

                        }

                    }
                    Log.i("wewewewwekljrejvij", mSelectedItem);
                    mDialogTraetyUnwindTvTwo.setText(value + "" + mSelectedItem);
                }
            }

        }

    }


}
